<!--  序列号维护 -->
<template>
  <basic-container>
    <div class="informationLabel el-tabs el-tabs--top el-tabs--border-card">
      <div class="el-tabs__header is-top">
        <div class="el-tabs__nav-wrap is-top">
          <div class="el-tabs__nav-scroll">
            <div role="tablist" class="el-tabs__nav is-top" style="transform: translateX(0px)">
              <div id="tab-0" aria-controls="pane-0" role="tab" aria-selected="true" tabindex="0" class="el-tabs__item is-top is-active">序列号维护搜索</div>
            </div>
          </div>
        </div>
        <div class="el-tabs__content" style="padding: 10px 10px 0 10px; background-color: #ffffff">
          <avue-form ref="serialNumRef" :option="serialNumManageOption" v-model="serialNumManageForm" @submit="handleSubmit" @reset-change="handleReset">
            <template slot-scope="" slot="menuForm">
              <el-button type="primary" icon="el-icon-search" @click="queryWorkOrderInfoAndSearch">搜 索</el-button>
              <el-button icon="el-icon-delete" @click="$refs.serialNumRef.resetForm()">清 空</el-button>
            </template>
            <template slot-scope="" slot="workOrderNo">
              <el-input placeholder="请选择工单号" v-model="serialNumManageForm.workOrderNo" @keyup.enter.native="queryWorkOrderInfo">
                <el-button slot="append" icon="el-icon-search" @click="openUserCommonModal({ type: 'workOrder' })"></el-button>
              </el-input>
            </template>
          </avue-form>
        </div>
      </div>
    </div>
    <div style="margin-top: 20px" class="informationLabel el-tabs el-tabs--top el-tabs--border-card">
      <div class="el-tabs__header is-top">
        <div class="el-tabs__nav-wrap is-top">
          <div class="el-tabs__nav-scroll">
            <div role="tablist" class="el-tabs__nav is-top" style="transform: translateX(0px)">
              <div id="tab-0" aria-controls="pane-0" role="tab" aria-selected="true" tabindex="0" class="el-tabs__item is-top is-active">
                序列号维护明细（已添加产品序列号： {{ selectionList.length }}条）
              </div>
            </div>
          </div>
        </div>
        <div class="el-tabs__content" style="padding: 20px 10px 0 10px; background-color: #ffffff">
          <avue-crud
            v-model="form"
            ref="crud"
            :option="option"
            :defaults.sync="defaults"
            :table-loading="loading"
            :data="data"
            :page.sync="page"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
          >
            <!-- 追溯，详情 -->
            <template slot="menu" slot-scope="scope">
              <el-button type="text" size="small" icon="el-icon-position" @click="handleAppend(scope.row)">追溯</el-button>
              <el-button type="text" size="small" icon="el-icon-view" @click="handleDetail(scope.row, scope.index)">详情</el-button>
              <el-button type="text" size="small" icon="el-icon-view" @click="handleSns(scope.row, scope.index)">外部序列号</el-button>
            </template>
            <template slot="menuRight">
              <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
            </template>
            <template slot="menuLeft">
              <el-button type="primary" size="small" icon="el-icon-position" v-if="permission.productSerialNumManage_jumpOperation" @click="handleJumpProcess"
                >跳转工序</el-button
              >
              <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
              <el-button type="warning" size="small" icon="el-icon-check" @click="handleChangeComplete">更改为完成</el-button>
              <el-button type="warning" size="small" icon="el-icon-check" @click="handleChangeInComplete">更改为未完成</el-button>
            </template>
          </avue-crud>
          <el-dialog
            class="dialogForm"
            v-dragDirectives
            ref="dialog"
            :title="dialogTitle"
            append-to-body
            :visible.sync="showDialog"
            :close-on-click-modal="false"
            top="5vh"
            width="70%"
            @close="closeDialog"
          >
            <avue-form ref="dialogForm" :option="dialogFormOption" v-model="dialogForm"></avue-form>
            <h3 class="custom-title"><i class="el-icon-vertical-bar mr10"></i>已选产品序列号</h3>
            <avue-crud :option="dialogTableOption" :data="dialogData">
              <template slot="menu" slot-scope="scope">
                <el-button type="text" size="small" icon="el-icon-delete" @click="productInfoRowDel(scope.$index)">删除</el-button>
              </template>
            </avue-crud>
            <span slot="footer" class="dialog-footer">
              <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
              <el-button type="primary" size="small" @click="submit"><i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
            </span>
          </el-dialog>
          <!-- 详情弹窗 -->
          <common-modal-template ref="detailCommonModalTemplate" :width="cmt.width" :title="cmt.title">
            <avue-crud v-model="detail.form" :data="detail.data" ref="detailForm" :option="detail.option"> </avue-crud>
          </common-modal-template>
          <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
        </div>
      </div>
    </div>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/product/query-product-sequence-number"
      :option="option"
      :page="page"
      :query="query"
      file-name="产品序列号"
      @success="exportSuccess"
    >
    </export-comp>
  </basic-container>
</template>

<script>
import {
  getList,
  skipRoute,
  getPassStationRecords,
  supplyPrint,
  getSnDetail,
  getGroupSns,
  getWorkOrderDetail,
  changeStatus,
  getProcess
} from '@/api/product/productSerialNumManage';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template2.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import SerialNumSelect from '@/views/product/components/serialNumSelect.vue';
import SerialNumOperate from '@/views/product/components/SerialNumOperate.vue';
import exportComp from '@/components/export-comp';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import ReworkInput from '@/views/product/components/reworkInput.vue';
export default {
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    SerialNumSelect,
    SerialNumOperate,
    exportComp,
    userTableConfig,
    ReworkInput
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'PRODUCT_SERIALNUM_MANAGE',
      rowData: null,
      skipInfo: null,
      detail: { form: {}, data: [], option: {} },
      query: {},
      // 自定义弹窗
      cmt: {
        title: '请选择工站',
        form: {
          skipRouteId: '',
          lockedReason: '',
          unlockedRemark: ''
        },
        option: {
          column: [
            {
              label: '工站',
              type: 'select',
              span: 24,
              prop: 'skipRouteId'
            },
            {
              label: '跳站原因',
              type: 'textarea',
              span: 24,
              prop: 'remark'
              // rules: [
              //   {
              //     required: true,
              //     message: '请输入跳站原因',
              //     trigger: 'blur'
              //   }
              // ]
            }
          ]
        }
      },
      selectionList: [],
      serialNumManageForm: {},
      serialNumManageOption: {
        menuSpan: 24,
        menuPosition: 'right',
        emptyBtn: false,
        submitBtn: false,
        searchLabelWidth: 90,
        column: [
          {
            label: '工单',
            // disabled: true,
            type: 'search',
            prop: 'workOrderNo',
            // readonly: true,
            span: 6,
            placeholder: '请选择工单号',
            rules: [
              {
                required: true,
                message: '请选择工单号',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({
                type: 'workOrder'
              });
            }
          },
          {
            label: '产品序列号',
            prop: 'sequenceNumber',
            // value: 'C82B6B16F3A9',
            span: 6,
            enter: (value) => {
              this.handleSnSearch(value);
            }
            // rules: [
            //   {
            //     required: true,
            //     message: '请输入产品序列号',
            //     trigger: 'blur'
            //   }
            // ]
          },
          {
            label: '所在工序',
            span: 6,
            prop: 'currRouteId',
            type: 'select',
            dicData: []
          },
          {
            label: '产品状态',
            span: 6,
            prop: 'status',
            type: 'select',
            dicData: [
              { label: '生产中', value: 1 },
              { label: '已完成', value: 2 },
              { label: '待不良判定', value: 3 },
              { label: '维修中', value: 4 },
              { label: '待出维修', value: 5 },
              { label: '锁定', value: 6 },
              { label: '报废', value: 7 },
              { label: '停用', value: 8 }
            ]
          }
        ]
      },
      workOrderId: '',
      data: [],
      page: {
        pageSizes: [20, 30, 40, 50, 100, 'all'],
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      loading: false,
      option: {
        height: 'calc(100vh - 520px)',
        rowKey: 'sequenceNumber',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        selection: true,
        reserveSelection: true,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        searchBtn: false,
        emptyBtn: false,
        refreshBtn: false,
        dialogClickModal: false,
        menu: true,
        menuWidth: 250,
        labelWidth: 150,
        defaultSort: {
          prop: 'sequenceNumber',
          order: 'descending'
        },
        columnBtn: false,
        column: [
          {
            label: '产品序列号',
            prop: 'sequenceNumber',
            order: 1,
            searchSpan: 8,
            // sortable: true,
            searchLabelWidth: 95
          },
          {
            label: '类型',
            order: 2,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            prop: 'productType'
          },
          {
            label: '所在工序',
            prop: 'routeName',
            order: 3,
            searchSpan: 8,
            type: 'select'
          },
          {
            label: '状态',
            prop: 'status',
            // slot: true,
            searchSpan: 8,
            order: 6,
            type: 'select',
            html: true,
            formatter: (val) => {
              if (val.status === 1) return `<span class="stateWords-success">生产中</span>`;
              else if (val.status === 2) return `<span class="stateWords-primary">已完成</span>`;
              else if (val.status === 3) return `<span class="stateWords-default">待不良判定</span>`;
              else if (val.status === 4) return `<span class="stateWords-danger">维修中</span>`;
              else if (val.status === 5) return `<span class="stateWords-danger">待出维修</span>`;
              else if (val.status === 6) return `<span class="stateWords-success">锁定</span>`;
              else if (val.status === 7) return `<span class="stateWords-success">报废</span>`;
              else if (val.status === 8) return `<span class="stateWords-warning">停用</span>`;
              else return '';
            },
            dicData: [
              { label: '生产中', value: 1 },
              { label: '已完成', value: 2 },
              { label: '待不良判定', value: 3 },
              { label: '维修中', value: 4 },
              { label: '待出维修', value: 5 },
              { label: '锁定', value: 6 },
              { label: '报废', value: 7 },
              { label: '停用', value: 8 }
            ]
          }
        ]
      },
      passStationList: [], // 可跳站列表
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      showDialog: false,
      dialogTitle: '',
      dialogForm: {},
      dialogFormOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '工序',
            type: 'select',
            span: 24,
            prop: 'toRouteId',
            display: true,
            rules: [
              {
                required: true,
                message: '请选择工序',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '跳转原因',
            type: 'textarea',
            span: 24,
            prop: 'remark',
            rules: [
              {
                required: true,
                message: '请输入跳转原因',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      dialogTableOption: {
        height: 400,
        calcHeight: 30,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '产品序列号',
            prop: 'sequenceNumber'
          },
          {
            label: '类型',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=part_type',
            prop: 'productType'
          },
          {
            label: '所在工序',
            prop: 'routeName'
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicData: [
              {
                label: '生产中',
                value: 1
              },
              {
                label: '已完成',
                value: 2
              },
              {
                label: '待不良判定',
                value: 3
              },
              {
                label: '维修中',
                value: 4
              },
              {
                label: '待出维修',
                value: 5
              },
              {
                label: '锁定',
                value: 6
              },
              {
                label: '报废',
                value: 7
              },
              {
                label: '停用',
                value: 8
              }
            ]
          }
        ]
      },
      dialogData: [],
      stationList: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    handleSnSearch(value) {
      if (!this.serialNumManageForm.workOrderNo) {
        this.$message.warning('请先选择工单号再进行搜索');
        return;
      }
      this.page.currentPage = 1;
      this.onLoad();
    },
    handleReset() {
      // this.page.currentPage = 1;
      // this.onLoad();
    },
    // 查询
    handleSubmit(form, done) {
      this.selectionClear();
      this.page.currentPage = 1;
      this.onLoad();
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad();
    },
    onLoad() {
      if (!this.serialNumManageForm.workOrderNo) {
        this.$message.warning('请输入工单号！');
        return;
      }
      this.loading = true;
      let params = {
        workOrderNo: this.serialNumManageForm.workOrderNo,
        workOrderId: this.serialNumManageForm.workOrderId,
        sn: this.serialNumManageForm.sequenceNumber,
        currRouteId: this.serialNumManageForm.currRouteId,
        status: this.serialNumManageForm.status,
        productType: this.serialNumManageForm.productType,
        descs: 'sequence_number'
      };
      this.query = params;
      getList(this.page.currentPage, this.page.pageSize, params)
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.exportData = this.data;
          // 回显基础信息
          // let workOrderSequenceNumberQueryVO = res.data.data.workOrderSequenceNumberQueryVO;
          // if (workOrderSequenceNumberQueryVO) {
          //   this.workNumManageForm = workOrderSequenceNumberQueryVO;
          // } else {
          //   for (const key in this.workNumManageForm) {
          //     this.workNumManageForm[key] = '';
          //   }
          // }
          // this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    // 跳转工序
    handleJumpProcess() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请至少选择一条数据');
        return;
      }
      let status = this.selectionList.every((item) => item.status !== 2);
      if (!status) {
        this.$message.warning('选择数据中包含完成序列号，不能进行跳转工序操作，请仔细检查！');
        return;
      }
      let selectRouteNames = this.selectionList.map((item) => item.routeName);
      let setSelectRouteNamesLen = new Set(selectRouteNames).size;
      if (setSelectRouteNamesLen > 1) {
        this.$message.warning('当前操作只支持同一种当前工序，请仔细检查！');
        return;
      }
      this.dialogTitle = '跳转工序';
      let toRouteId = this.findObject(this.dialogFormOption.column, 'toRouteId');
      toRouteId.display = true;
      let remark = this.findObject(this.dialogFormOption.column, 'remark');
      remark.label = '跳转原因';
      remark.rules[0].message = '请输入跳转原因';
      let index = this._findIndex(this.stationList, { label: this.selectionList[0].routeName });
      if (index != -1) {
        toRouteId.dicData = this.stationList.slice(0, index);
        if (toRouteId.dicData.length === 0) {
          this.$message.warning('当前没有可跳转的工序！');
          return;
        }
      } else {
        this.$message.warning('工单工艺路线中不存在当前工序！');
        return;
      }
      this.showDialog = true;
      this.dialogData = this._cloneDeep(this.selectionList);
    },
    productInfoRowDel(index) {
      this.dialogData.splice(index, 1);
    },
    submit() {
      if (this.dialogTitle === '跳转工序') {
        if (!this.dialogForm.toRouteId) {
          this.$message.warning('请选择跳转工序！');
          return;
        }
        if (!this.dialogForm.remark) {
          this.$message.warning('请输入跳转原因！');
          return;
        }
        if (this.dialogData.length === 0) {
          this.$message.warning('已选产品序列号不能为空！');
          return;
        }
        let ids = this.dialogData.map((item) => item.id);
        skipRoute({ workOrderId: this.workOrderId, productIds: ids, toRouteId: this.dialogForm.toRouteId, remark: this.dialogForm.remark }).then((res) => {
          this.$message.success('跳转成功！');
          this.showDialog = false;
          this.onLoad();
          this.selectionClear();
        });
      } else {
        if (!this.dialogForm.remark) {
          this.$message.warning('请输入更改原因！');
          return;
        }
        if (this.dialogData.length === 0) {
          this.$message.warning('已选产品序列号不能为空！');
          return;
        }
        let msg = '';
        let statusAction = '';
        if (this.dialogTitle === '更改为完成') {
          msg = '确认将所选SN的状态修改为完成？';
          statusAction = 'finish';
        } else {
          msg = '确认将所选SN的状态修改为未完成？';
          statusAction = 'unfinish';
        }
        this.$confirm(msg, {
          type: 'warning'
        }).then(() => {
          let ids = this.dialogData.map((item) => item.id).join(',');
          changeStatus({ ids: ids, statusAction: statusAction, remark: this.dialogForm.remark }).then((res) => {
            this.$message.success('更改成功！');
            this.showDialog = false;
            this.onLoad();
            this.selectionClear();
          });
        });
      }
    },
    handleAppend(row) {
      this.$router.push({
        path: '/report/forward-trace-back-to',
        query: {
          sequenceNumber: row.sequenceNumber
        }
      });
    },
    handleDetail(row, index) {
      this.$refs.detailCommonModalTemplate.showModal();
      this.detail.option.column = [];
      this.cmt.title = '详情';
      this.cmt.width = '80%';
      this.detail.option = {
        labelWidth: 130,
        menu: false,
        addBtn: false,
        refreshBtn: false,
        columnBtn: false,
        border: true,
        calcHeight: 30,
        index: true,
        indexLabel: '序号',
        page: false,
        column: [
          {
            label: '产品序列号',
            prop: 'productSequenceNo'
          },
          {
            label: '原工序',
            prop: 'fromRouteName'
          },
          {
            label: '变更工序',
            prop: 'toRouteName'
          },
          {
            label: '跳站原因',
            type: 'textarea',
            prop: 'skipComment'
          },
          {
            label: '跳站时间',
            prop: 'createTime'
          }
        ]
      };
      getSnDetail(row.productId).then((res) => {
        let data = res.data.data;
        this.detail.data = data;
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 生产订单
        case 'workOrder':
          this.modalName = 'workOrderModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择工单信息（双击进行选择）',
            url: '/api/mes-product/work-order/page',
            titleInfo: 'workOrderModal',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'WORKORDER'
          };
          break;
        // 包装配置
        case 'packingConfig':
          this.modalName = 'packingConfigModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择包装配置（双击进行选择）',
            url: `/api/mes-admin/productpackingconfig/page?partNo=${this.form.partNo}`,
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'productpacking'
          };
          break;
        // 打印机
        case 'print':
          this.modalName = 'printersModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择打印机（双击进行选择）',
            url: '/api/mes-product/ems-equipment/page?type=PRINTER',
            isPage: true,
            rowSelectionType: 'single',
            templateName: 'PRINTER'
          };
          break;
        // 标签模板
        case 'template':
          this.modalName = 'labelTemplateModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择标签模版（双击进行选择）',
            url: `/api/mes-admin/labeltemplate/page?type=material&subType=work_in_progress&status=1`,
            isPage: true,
            rowSelectionType: 'single',
            templateName: 'LABELTEMPLATE'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderModal':
          let serialNumManageOptionColumn = this.serialNumManageOption.column;
          let currRouteNameIndex = serialNumManageOptionColumn.findIndex((col) => col.prop == 'currRouteId');
          serialNumManageOptionColumn[currRouteNameIndex].dicData = [];
          this.serialNumManageForm.currRouteId = '';
          this.serialNumManageForm.workOrderNo = this._get(rowData, 'workOrderNo', '');
          this.serialNumManageForm.workOrderId = this._get(rowData, 'id', '');
          this.workOrderId = this._get(rowData, 'id', '');

          this.serialNumManageForm.objectDimensionName = this._get(rowData, 'name', '');
          this.serialNumManageForm.objectName = this._get(rowData, 'partName', '');
          this.serialNumManageForm.objectNo = this._get(rowData, 'partNo', '');
          this.serialNumManageForm.objectModel = this._get(rowData, 'partModel', '');
          this.serialNumManageForm.categoryName = this._get(rowData, 'categoryName', '');

          // 据工单号查询工序列表
          getProcess(rowData.id)
            .then((res) => {
              let data = this._get(res, 'data.data.processRouteVOList', []);
              serialNumManageOptionColumn[currRouteNameIndex].dicData = data.map((d) => {
                return {
                  label: d.routeName,
                  value: d.id
                };
              });
              serialNumManageOptionColumn[currRouteNameIndex].dicData.unshift({
                label: '全部',
                value: ''
              });
              this.stationList = data.map((d) => {
                return {
                  label: d.routeName,
                  value: d.id
                };
              });
            })
            .catch((err) => {});
          break;
        case 'printersModal':
          this.retag.form.printersName = this._get(rowData, 'name', '');
          this.retag.form.printersId = this._get(rowData, 'id', '');
          break;
        case 'labelTemplateModal':
          this.retag.form.labelTemplateName = this._get(rowData, 'labelName', '');
          this.retag.form.labelTemplateId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    handleChangeComplete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      } else if (this.selectionList.length === 1) {
        let status = this.selectionList[0].status;
        if (status == '1') {
          this.$message.warning('该产品已完成，不需要更改为完成状态！');
          return;
        }
        if (status == '4') {
          this.$message.warning('该产品已报废！不允许更改为完成状态！');
          return;
        }
        if (status == '6') {
          this.$message.warning('该产品正在维修，请维修完成后操作！');
          return;
        }
        if (status == '8') {
          this.$message.warning('该产品已锁定，请解锁后操作！');
          return;
        }
        this.showDialog = true;
        this.dialogTitle = '更改为完成';
        let toRouteId = this.findObject(this.dialogFormOption.column, 'toRouteId');
        toRouteId.display = false;
        let remark = this.findObject(this.dialogFormOption.column, 'remark');
        remark.label = '更改原因';
        remark.rules[0].message = '请输入更改原因';
        this.dialogData = this._cloneDeep(this.selectionList);
      } else if (this.selectionList.length > 1) {
        let allStatus = this.selectionList.every((item) => item.status == 0);
        if (!allStatus) {
          this.$message.warning('仅支持状态为生产中的产品更改为完成，请仔细检查！');
          return;
        } else {
          this.showDialog = true;
          this.dialogTitle = '更改为完成';
          let toRouteId = this.findObject(this.dialogFormOption.column, 'toRouteId');
          toRouteId.display = false;
          let remark = this.findObject(this.dialogFormOption.column, 'remark');
          remark.label = '更改原因';
          remark.rules[0].message = '请输入更改原因';
          this.dialogData = this._cloneDeep(this.selectionList);
        }
      }
    },
    handleChangeInComplete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      } else if (this.selectionList.length === 1) {
        let status = this.selectionList[0].status;
        if (status == '1') {
          this.showDialog = true;
          this.dialogTitle = '更改为未完成';
          let toRouteId = this.findObject(this.dialogFormOption.column, 'toRouteId');
          toRouteId.display = false;
          let remark = this.findObject(this.dialogFormOption.column, 'remark');
          remark.label = '更改原因';
          remark.rules[0].message = '请输入更改原因';
          this.dialogData = this._cloneDeep(this.selectionList);
        }
        if (status == '4') {
          this.$message.warning('该产品已报废！不允许更改为未完成状态！');
          return;
        }
        if (status == '6') {
          this.$message.warning('该产品正在维修，请维修完成后操作！');
          return;
        }
        if (status == '8') {
          this.$message.warning('该产品已锁定，请解锁后操作！');
          return;
        }
        if (status == '0') {
          this.$message.warning('该产品已经是生产中状态，不需要更改为未完成状态！');
          return;
        }
      } else if (this.selectionList.length > 1) {
        let allStatus = this.selectionList.every((item) => item.status == 1);
        if (!allStatus) {
          this.$message.warning('仅支持状态为完成的产品更改为未完成，请仔细检查！');
          return;
        } else {
          this.showDialog = true;
          this.dialogTitle = '更改为未完成';
          let toRouteId = this.findObject(this.dialogFormOption.column, 'toRouteId');
          toRouteId.display = false;
          let remark = this.findObject(this.dialogFormOption.column, 'remark');
          remark.label = '更改原因';
          remark.rules[0].message = '请输入更改原因';
          this.dialogData = this._cloneDeep(this.selectionList);
        }
      }
    },
    retagSubmit(form, done) {
      let productIds = this.selectionList.map((p) => p.productId);
      let sequenceGenerationId = this.selectionList[0].sequenceGenerationId;
      supplyPrint({
        equipmentId: this.retag.form.printersId,
        labelTemplateId: this.retag.form.labelTemplateId,
        workOrderId: this.selectionList[0].workOrderId,
        productIds: productIds,
        sequenceGenerationId
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message.success('打印成功');
            this.retag.visible = false;
            this.$refs.retagForm.resetFields();
            done();
            this.selectionClear();
          }
        })
        .catch((err) => {});
    },
    exportSuccess(status) {
      if (status) {
        this.selectionClear();
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    queryWorkOrderInfo() {
      if (!this.serialNumManageForm.workOrderNo) {
        return;
      }
      getWorkOrderDetail(this.serialNumManageForm.workOrderNo).then((res) => {
        let serialNumManageOptionColumn = this.serialNumManageOption.column;
        let currRouteNameIndex = serialNumManageOptionColumn.findIndex((col) => col.prop == 'currRouteId');
        serialNumManageOptionColumn[currRouteNameIndex].dicData = [];
        this.serialNumManageForm.currRouteId = '';
        this.serialNumManageForm.workOrderNo = this._get(res, 'data.data.orderNo', '');
        this.serialNumManageForm.workOrderId = this._get(res, 'data.data.id', '');

        this.serialNumManageForm.objectDimensionName = this._get(res, 'data.data.name', '');
        this.serialNumManageForm.objectName = this._get(res, 'data.data.partName', '');
        this.serialNumManageForm.objectNo = this._get(res, 'data.data.partNo', '');
        this.serialNumManageForm.objectModel = this._get(res, 'data.data.partModel', '');
        this.serialNumManageForm.categoryName = this._get(res, 'data.data.categoryName', '');
        this.$refs.serialNumRef.submit();

        // 据工单号查询工序列表
        getRoutesByWo(this.serialNumManageForm.workOrderId)
          .then((res) => {
            let data = res.data.data;
            serialNumManageOptionColumn[currRouteNameIndex].dicData = data.map((d) => {
              return {
                label: d.name,
                value: d.id
              };
            });
            serialNumManageOptionColumn[currRouteNameIndex].dicData.unshift({
              label: '全部',
              value: ''
            });
            console.log('data', data);
          })
          .catch((err) => {});
      });
    },
    queryWorkOrderInfoAndSearch() {
      if (!this.serialNumManageForm.workOrderNo) {
        this.$message.warning('请输入工单号！');
        return;
      }
      // getWorkOrderDetail(this.serialNumManageForm.workOrderNo).then((res) => {
      //   let serialNumManageOptionColumn = this.serialNumManageOption.column;
      //   let currRouteNameIndex = serialNumManageOptionColumn.findIndex((col) => col.prop == 'currRouteId');
      //   serialNumManageOptionColumn[currRouteNameIndex].dicData = [];
      //   this.serialNumManageForm.workOrderNo = this._get(res, 'data.data.orderNo', '');
      //   this.serialNumManageForm.workOrderId = this._get(res, 'data.data.id', '');

      //   this.serialNumManageForm.objectDimensionName = this._get(res, 'data.data.name', '');
      //   this.serialNumManageForm.objectName = this._get(res, 'data.data.partName', '');
      //   this.serialNumManageForm.objectNo = this._get(res, 'data.data.partNo', '');
      //   this.serialNumManageForm.objectModel = this._get(res, 'data.data.partModel', '');
      //   this.serialNumManageForm.categoryName = this._get(res, 'data.data.categoryName', '');

      //   // 据工单号查询工序列表
      //   getRoutesByWo(this.serialNumManageForm.workOrderId)
      //     .then((res) => {
      //       let data = res.data.data;
      //       serialNumManageOptionColumn[currRouteNameIndex].dicData = data.map((d) => {
      //         return {
      //           label: d.name,
      //           value: d.id
      //         };
      //       });
      //       serialNumManageOptionColumn[currRouteNameIndex].dicData.unshift({
      //         label: '全部',
      //         value: ''
      //       });
      //       let currRouteId = this._find(serialNumManageOptionColumn[currRouteNameIndex].dicData, { value: this.serialNumManageForm.currRouteId });
      //       if (!currRouteId) {
      //         this.serialNumManageForm.currRouteId = '';
      //       }
      this.$refs.serialNumRef.submit();
      //       console.log('data', data);
      //     })
      //     .catch((err) => {
      //       this.serialNumManageForm.currRouteId = '';
      //       this.$refs.serialNumRef.submit();
      //     });
      // });
    }
  }
};
</script>

<style lang="scss" scoped>
@mixin common-modal-sub-title {
  .common-modal-sub-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .el-icon-vertical-bar {
      height: 20px;

      &::before {
        width: 5px;
        height: 100%;
      }
    }

    .sub-title {
      margin-left: 10px;
      font-size: 18px;
      font-weight: bold;

      .add-text {
        font-size: 16px;
      }
    }
  }
}

.serialNumManage {
  @include common-modal-sub-title();
}

.serialNumWrap {
  @include common-modal-sub-title();
}

.transmit {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  ::v-deep .trans {
    font-size: 24px;
    margin-bottom: 15px;
    cursor: pointer;
  }
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
.custom-title {
  font-size: 16px;
  font-weight: bold;
  .mr10 {
    margin-right: 10px;
  }
}
.dialogForm {
  ::v-deep .el-card__body {
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
